import json
from dateutil.relativedelta import relativedelta
from decimal import Decimal
from apps.user.dao import UserDao
from apps.system.rank.dao import RankDao
from apps.system.activityPerformance.dao import ActivityPerformanceDao
from django.db.models import F

# 升级
def updateTeamRank(user, activity):
    if user.id:
        _user = UserDao().findOneByObjId(user.id)
        _activityPerformance = None
        _activityPerformances = ActivityPerformanceDao().findAll().filter(activity=activity, user=_user)
        if _activityPerformances.exists():
            _activityPerformance = _activityPerformances.first()


        _ranks = RankDao().findAll().order_by('-grade')
        for rank in _ranks:
            if rank.grade <= 0:
                break

            _users = UserDao().findAll().filter(parent=_user, rank__grade__gte=rank.grade-1, role='custom')
            # print('如果满足条件，升级到下一个级别', _user, _users.count(), rank.teamPerformance, rank.verticalPeopleNumber, rank.grade)
            if _activityPerformance.teamPerformance >= rank.teamPerformance and _users.count() >= rank.verticalPeopleNumber:
                if _user.rank.grade < rank.grade:
                    _user.rank = rank
                    _user.save()
                    break

        if _user.parent:
            updateTeamRank(_user.parent, activity)
    else:
        return False